#实现qq登录的购物车合并
import base64
import pickle
from django_redis import get_redis_connection

def merge_cart_cookie_to_redis(request,user,response):

    #读取cookie中的购物车数据
    cookie_cart_str = request.COOKIES.get('cart')

    if not cookie_cart_str:
        return response

    # """
    # {
    #     sku_id10: {
    #         "count": 10,  // 数量
    #         "selected": True  // 是否勾选
    #     },
    #     sku_id20: {
    #         "count": 20,
    #         "selected": False
    #     },
    #     ...
    # }
    # """
    cookie_cart_str_bytes = cookie_cart_str.encode()
    cookie_cart_dict_bytes = base64.b64decode(cookie_cart_str_bytes)
    cookie_cart_dict = pickle.loads(cookie_cart_dict_bytes)

    # {
    #     b'sku_id_1':b'count_1',
    #     b'sku_id_2': b'count_2',
    # }

    #读取redis中的购物车数据
    redis_conn = get_redis_connection('cart')
    redis_cart_dict = redis_conn.hgetall('cart_%s'%user.id)
    redis_cart_selected = redis_conn.smembers('selected_%s'%user.id)

    # [b'sku_id_1', b'sku_id_2']

    #遍历cookie中的购物车数据，合并到redis(核心代码)
    new_redis_cart_dict = {}

    for sku_id,count in redis_cart_dict.items():
        new_redis_cart_dict[int(sku_id)] = int(count)

    for sku_id,cart_dcit in cookie_cart_dict.items():
        new_redis_cart_dict[sku_id] = cart_dcit['count']

        if cart_dcit['selected']:
            redis_cart_selected.add(sku_id)

    pl = redis_conn.pipeline()
    pl.hmset('cart_%s'%user.id,new_redis_cart_dict)
    pl.sadd('selected_%s'%user.id,*redis_cart_selected)
    pl.execute()

    #清空cookie
    response.set_cookie('cart')

    # 只有返回了响应对象，cookie才有机会被执行的
    return response